package com.ruoyi.web.controller.api;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.jwt.JwtHelper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.demo.domain.LoginParam;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.Pattern;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fgr
 */

@Controller
@RequestMapping("/api/login")
public class ApiLoginController extends ApiBaseController{

    @Autowired
    private ISysUserService userService;
    
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> ajaxLogin(@RequestBody LoginParam param)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(param.getUsername(), param.getPassword(), false);
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> result = new HashMap<String, Object>();
        try
        {
            subject.login(token);
            SysUser sysUser = userService.selectUserByLoginName(param.getUsername());
            String jwtToken = JwtHelper.generateToken(sysUser.getUserId().toString());
//        String jwtToken = JwtHelper.generateToken("openId", member.getWxId());
            result.put("token", jwtToken);
            result.put("userInfo", sysUser);
            return result;
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }
}
